import {AppFileInfo, TaskConfig} from "../TaskBean";
import path from "path";
import {FileUtil} from "@ohos/hvigor";
import fs from "fs";
import {Logger} from "../utils/Logger";
import {logNowTime} from "../utils/CommonUtils";

export interface DeleteAppTaskConfig extends TaskConfig {
    saveAppDir?: string[]
    maxFileNum?: number
}

const TAG = 'DeleteAppTask'

export function deleteExcessAppFileTask(config?: DeleteAppTaskConfig) {
    if (!config) {
        config = {debug: false, saveAppDir: []}
    }
    Logger.debug = config.debug ?? false
    let saveAppDir = config.saveAppDir
    if (!saveAppDir || saveAppDir.length <= 0) {
        Logger.error(TAG, 'saveAppDir is empty,def:_hap,_app')
        saveAppDir = []
        saveAppDir.push("_hap", "_app")
    }
    Logger.info(TAG, "=======================deleteExcessAppFilePlugin=========================")
    for (const dir of saveAppDir) {
        const dirPath = path.resolve(dir)
        const isExist = FileUtil.exist(dirPath)

        Logger.info(TAG, "isExist:" + isExist + ",dirPath:" + dirPath)
        if (isExist) {
            deleteAppFile(dirPath, config.maxFileNum ?? 5);
        }
    }
    logNowTime()
}

function deleteAppFile(dirPath: string, maxFileNum: number) {
    if (maxFileNum <= 1) {
        maxFileNum = 5
    }
    Logger.info(TAG, "rootPath:" + dirPath)
    if (!fs.existsSync(dirPath)) {
        Logger.info(TAG, dirPath + " not exist")
        return
    }
    const hapFileInfos: AppFileInfo[] = []
    let files = fs.readdirSync(dirPath);
    if (!files || files.length <= 0) {
        Logger.info(TAG, "no files in " + dirPath)
        return;
    }
    for (let i = 0; i < files.length; i++) {
        let filePath = path.join(dirPath, files[i]);
        Logger.info(TAG, "app path:" + filePath)
        const state = fs.statSync(filePath)
        if (state.isFile()) {
            hapFileInfos.push({createTimeMS: state.mtimeMs, filePath: filePath})
        }
    }
    if (hapFileInfos.length > maxFileNum) {
        hapFileInfos.sort((a, b) => b.createTimeMS - a.createTimeMS)

        Logger.info(TAG, "appFileInfos:", hapFileInfos)

        const needDeleteData = hapFileInfos.slice(maxFileNum)

        Logger.info(TAG, "needDeleteData:", needDeleteData)

        for (const file of needDeleteData) {
            fs.unlinkSync(file.filePath)
        }
    }
}